<template>
  <div class="exclusive-seat">
    <div class="countent">
      <div class="title">
        <breadCrumb @back="returnFun" :titleArr="titleArr"></breadCrumb>
      </div>
      <div class="exclusive-seat-box clearBoth">
        <div class="exclusive-seat-all">
          <span v-for="(item, index) in exclusiveSeatList" class="enabled"
                :class="exclusiveSeatListIndex === index ? 'exclusiveSeat-active' : ''"
                @click="editExclusiveSeat(item, index)"
                :title="item.name" :key="index">{{item.name}}</span>
        </div>
        <el-button class="exclusive-seat-box-btn primary_btn" @click="addexclusiveSeat">{{$t('configLazyLoad.channel.addExclusiveAgent')}}</el-button>
      </div>
      <div class="add-exclusiveSeat-add mail_category_add" v-show="addexclusiveSeatShow" v-loading="editLoading">
        <el-form ref="addexclusiveSeatAdd" :model="addexclusiveSeatAdd" :rules="rules" label-width="160px" label-position="right">
          <el-form-item :label="$t('configLazyLoad.channel.exclusiveName')" :placeholder="$t('configLazyLoad.channel.inputExclusiveName')" class="exclusive-seat-li exclusive-seat-from-li" prop="name">
            <el-input v-model="addexclusiveSeatAdd.name" class="exclusive-seat-li-input"></el-input>
          </el-form-item>
          <div class="select-tree">
            <el-popover
              ref="popover4"
              placement="bottom"
              v-model="treeShow"
              :visible-arrow="false"
              trigger="click">
              <el-tree
                class="filter-tree"
                :data="agentOptions"
                node-key="_id"
                :empty-text="$t('configLazyLoad.channel.noMatchData')"
                default-expand-all
                accordion
                :filter-node-method="filterNode"
                @node-click="nodeClickFun"
                ref="tree">
              </el-tree>
            </el-popover>
            <el-form-item :label="$t('configLazyLoad.channel.agent2')" class="exclusive-seat-li exclusive-seat-from-li" required>
              <el-input
                class="exclusive-seat-li-input"
                :placeholder="seatValue"
                v-model="filterText"
                v-popover:popover4>
              </el-input>
            </el-form-item>
          </div>
          <el-form-item class="exclusive-seat-from-li exclusive-seat-li" :label="$t('configLazyLoad.channel.agentTip1')" prop="skillGroup">
            <el-select :placeholder="$t('call.placeSkillsGrouop')" class="exclusive-seat-li-input" v-model="addexclusiveSeatAdd.skillGroup">
              <el-option
                v-for="(item, index) in mailQueues"
                :label="item.DisplayName"
                :key="index"
                :value="item._id">
              </el-option>
            </el-select>
          </el-form-item>
          <div>
            <div class="email-notice">{{$t('configLazyLoad.channel.agentTip2')}}</div>
            <el-form-item class="exclusive-seat-li exclusive-seat-li-email" :label="$t('configLazyLoad.channel.sendAddress')" v-for="(condition, index) in addexclusiveSeatAdd.fromAddr" required>
              <el-form-item class="conditions_li_text" :prop="'fromAddr.' + index + '.value'" :rules="rules.email">
                <el-input v-model.trim="condition.value" class="condition_li" :placeholder="$t('configLazyLoad.channel.addEmail')"></el-input>
                <span v-if="index === 0" @click="addDomain(condition)" class="el-icon-plus domain_btn"></span>
                <span v-else @click="removeDomain(condition)" class="el-icon-minus domain_btn"></span>
              </el-form-item>
            </el-form-item>
          </div>
          <el-form-item>
            <div class="btn_box clearBoth exclusiveSeatBtn">
              <el-button @click="saveForm('addexclusiveSeatAdd')" type="primary" class="primary_btn">{{$t('public.save')}}</el-button>
              <el-button v-show="exclusiveSeatType === 'edit'" type="danger" class="primary_btn" @click="deleteFun">{{$t('public.delete')}}</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  import breadCrumb from '../../../../ui-modules/breadCrumb/BreadCrumbConfig.vue'
  import {getCache, deepClone} from '@/utils/m7Utils.js'
  export default {
    name: 'firmMailExclusiveSeat',
    data () {
      return {
        titleArr: [this.$t('configLazyLoad.channel.mailTip8'), this.$t('configLazyLoad.channel.exclusiveAgentSetting')],
        addexclusiveSeatAdd: { // 专属座席表单
          name: '', // 名称
          seatId: '', // 座席id
          fromAddr: [{value: ''}], // 发件人地址
          skillGroup: '' // 技能组
        },
        addexclusiveSeatShow: false, // 专属座席是否显示
        editLoading: false,
        agentOptions: [], // 座席
        seatValue: '', // 座席值
        filterText: '', // 座席筛选
        treeShow: false, // 座席树
        mailQueues: '', // 技能组
        exclusiveSeatList: '', // 专属坐席列表
        exclusiveSeatType: 'add', // 专属座席类型
        exclusiveSeatListIndex: 0, // 专属座席列表索引
        excluseiveSeatId: '', // 专属座席类型id
        rules: {
          name: [{required: true, message: this.$t('configLazyLoad.channel.inputExclusiveName'), trigger: 'blur'}], // 名称
          skillGroup: [{required: true, message: this.$t('configLazyLoad.channel.selectTransGroup'), trigger: 'change'}], // 技能组
          email: [{required: true, message: this.$t('configLazyLoad.channel.inputEmailAddress'), trigger: 'blur'}, // 收件人邮箱
            { pattern: /^[a-z0-9A-Z]+([._\\-]*[a-z0-9A-Z])*@([a-z0-9A-Z]+[-a-z0-9A-Z]*[a-z0-9A-Z]+.){1,63}[a-z0-9A-Z]+$/, message: this.$t('configLazyLoad.channel.inputCorrectEmailAddress') }]
        }
      }
    },
    created () {
      this.getTreeData()
      this.getExclusiveSeatListFun(0)
      this.mailQueues = deepClone(getCache('mailQueues')) // 获取技能组
    },
    methods: {
      returnFun () { // 取消事件
        this.$emit('cancel')
      },
      addexclusiveSeat () { // 添加专属座席按钮事件
        this.exclusiveSeatType = 'add'
        this.exclusiveSeatListIndex = -1
        this.addexclusiveSeatShow = true
        this.addexclusiveSeatAdd.name = ''
        this.seatValue = ''
        this.addexclusiveSeatAdd.skillGroup = ''
        this.addexclusiveSeatAdd.fromAddr = [{value: ''}]
      },
      filterNode (value, data) { // 座席筛选事件
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      nodeClickFun (data) { // 座席选中后事件
        if (data.type === 'agent') {
          this.seatValue = data.label
          this.addexclusiveSeatAdd.seatId = data._id
          this.treeShow = false
          this.filterText = ''
        }
      },
      getExclusiveSeatListFun (index) { // 获取专属座席列表
        let data = {relateEmailAddr: this.exclusiveSeatData.email}
        this.$store.dispatch('getExclusiveSeatList', data)
          .then(res => {
            this.exclusiveSeatList = res.list
            if (this.exclusiveSeatList.length > 0) { // 专属座席列表为空时 表单不显示
              this.editExclusiveSeat(this.exclusiveSeatList[index], index)
            }
          })
      },
      getTreeData () { // 获取座席树
        Promise.all([
          this.$store.dispatch('getCache', { type: 'depts' }),
          this.$store.dispatch('getCache', { type: 'agents' })
        ]).then(([depts, agents]) => {
          let optionData = []
          dealDept(depts, optionData, '')
          dealAgent(agents, optionData[0].children)
          let noDeptAgents = agents.filter(agent => agent.status === 'enable' && !agent.deptId).map(agent => (
            { _id: agent._id, type: 'agent', label: `${agent.displayName} ${agent.exten}`, pinyin: agent.pinyin })
          )
          optionData[0].children.push(...noDeptAgents)
          setDeptAgentCount(optionData[0])
          this.agentOptions = optionData
        })
      },
      addDomain () { // 添加邮箱地址事件
        this.addexclusiveSeatAdd.fromAddr.push({value: ''})
      },
      removeDomain (item) { // 移除邮箱地址事件
        var index = this.addexclusiveSeatAdd.fromAddr.indexOf(item)
        if (index !== -1) {
          this.addexclusiveSeatAdd.fromAddr.splice(index, 1)
        }
      },
      editExclusiveSeat (data, index) { // 修改专属座席事件
        this.exclusiveSeatListIndex = index
        this.addexclusiveSeatShow = true
        this.excluseiveSeatId = data._id
        this.exclusiveSeatType = 'edit'
        this.addexclusiveSeatAdd.name = data.name
        this.seatValue = data.seat.displayName
        this.addexclusiveSeatAdd.skillGroup = data.peer._id
        this.addexclusiveSeatAdd.fromAddr = data.fromAddr
        this.addexclusiveSeatAdd.seatId = data.seatId
      },
      saveForm (addexclusiveSeatAdd) { // 专属座席提交事件
        let count = 0
        let exclusiveSeatName = '' || this.addexclusiveSeatAdd.name
        this.exclusiveSeatList.forEach(exclusiveSeatListItem => {
          exclusiveSeatListItem.fromAddr.forEach(fromItem => {
            this.addexclusiveSeatAdd.fromAddr.forEach(item => {
              if (this.exclusiveSeatType === 'edit') { // 编辑
                if (exclusiveSeatListItem.name !== this.exclusiveSeatList[this.exclusiveSeatListIndex].name && item.value === fromItem.value) { // 判断邮件地址是否重复
                  exclusiveSeatName = exclusiveSeatListItem.name
                  count += 1
                }
              } else if (item.value === fromItem.value) { // 添加
                exclusiveSeatName = exclusiveSeatListItem.name
                count += 1
              }
            })
          })
        })
        let naryArr = []
        for (let i in this.addexclusiveSeatAdd.fromAddr) {
          naryArr.push(this.addexclusiveSeatAdd.fromAddr[i].value)
        }
        let nary = naryArr.sort()
        for (var i = 0; i < nary.length - 1; i++) {
          if (nary[i] === nary[i + 1]) {
            count += 1
          }
        }
        if (count > 0) {
          this.$message.error(this.$t('configLazyLoad.channel.agentTip3',{name: exclusiveSeatName}))
          return false
        } else {
          this.$refs[addexclusiveSeatAdd].validate((valid) => {
            if (valid) {
              let data = {
                name: this.addexclusiveSeatAdd.name,
                seatId: this.addexclusiveSeatAdd.seatId,
                relateEmailAddr: this.exclusiveSeatData.email,
                toPeer: this.addexclusiveSeatAdd.skillGroup,
                fromAddr: this.addexclusiveSeatAdd.fromAddr
              }
              if (this.seatValue === '') {
                this.$message.error(this.$t('configLazyLoad.channel.agentTip4'))
                return false
              }
              if (this.exclusiveSeatType === 'add') { // 添加
                this.$store.dispatch('saveFirmExclusiveSeat', data).then(res => {
                  this.getExclusiveSeatListFun(this.exclusiveSeatList.length)
                })
              } else if (this.exclusiveSeatType === 'edit') { // 修改
                data._id = this.excluseiveSeatId
                this.$store.dispatch('saveFirmExclusiveSeat', data).then(res => {
                  this.getExclusiveSeatListFun(this.exclusiveSeatListIndex)
                })
              }
              this.addexclusiveSeatShow = false
            }
          })
        }
      },
      deleteFun () { // 专属座席删除事件
        this.$confirm(
          this.$t('public.confirmDel'), this.$t('public.operate'), {
            confirmButtonText: this.$t('public.confirm'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          })
          .then(() => {
            let data = {_id: this.exclusiveSeatList[this.exclusiveSeatListIndex]._id}
            this.$store.dispatch('deleteFirmExclusiveSeat', data)
              .then(res => {
                if (res && res.success) {
                  this.$message.success(this.$t('configLazyLoad.channel.exclusiveAgentDeleteSuc'))
                  this.addexclusiveSeatShow = false
                  this.exclusiveSeatListIndex = -1
                  this.getExclusiveSeatListFun(0)
                } else {
                  this.$message.error(this.$t('configLazyLoad.channel.exclusiveAgentDeleteFail'))
                }
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: this.$t('configLazyLoad.channel.exclusiveAgentDeleteFail')
            })
          })
      }
    },
    props: {
      exclusiveSeatData: { // 专属座席数据
        type: Object,
        default () {
          return {}
        }
      }
    },
    watch: {
      filterText (val) {
        this.$refs.tree.filter(val)
      }
    },
    coumpted: {
      exclusiveSeatName () {
        return this.exclusiveSeatName
      }
    },
    components: {
      breadCrumb
    }
  }
  function dealDept (depts, arr, key) {
    for (let i = 0; i < depts.length; i++) {
      let dept = depts[i]
      if (dept.pId === key) {
        let obj = {
          _id: dept._id,
          type: 'dept',
          label: dept.name,
          order: dept.order,
          children: []
        }
        arr.push(obj)
        dealDept(depts, obj.children, dept._id)
      }
    }
  }
  function dealAgent (agents, arr) {
    if (!arr) {
      return
    }
    for (let i = 0; i < arr.length; i++) {
      dealAgent(agents, arr[i].children)
      let deptAgents = agents.filter(agent => agent.status === 'enable' && agent.deptId === arr[i]._id)
      deptAgents = deptAgents.map(agent => ({
        _id: agent._id,
        type: 'agent',
        label: `${agent.displayName} ${agent.exten}`,
        pinyin: agent.pinyin }))
      arr[i].children.push(...deptAgents)
    }
  }
  function setDeptAgentCount (obj) {
    if (!obj.children && obj.type === 'agent') {
      return 1
    }
    let count = 0
    for (let i = 0; i < obj.children.length; i++) {
      count += setDeptAgentCount(obj.children[i])
    }
    obj.label = `${obj.label} (${count})`
    return count
  }
</script>
<style lang="stylus">
  .filter-tree .el-tree-node >.el-tree-node__children
    overflow visible
  .select-tree input::-webkit-input-placeholder
    color #1a1a1a !important
</style>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .countent
    .exclusive-seat-box
      border-bottom 1px solid #ccc
      padding 10px 0
      font-size 12px
      span
        cursor pointer
        padding 4px 10px
        margin 0 8px
        display inline-block
        max-width 90px
        overflow hidden
        white-space nowrap
        text-overflow ellipsis
      .exclusive-seat-box-btn
        float right
        margin-right: 40px
      .exclusive-seat-all
        display inline-block
        float left
        max-width calc(100vw - 400px)
        .enabled
          border-radius 4px
          color $c-main
          border 1px solid #fff
    .add-exclusiveSeat-add
      font-size 12px
      padding-top 10px
      margin-left 10px
    .exclusive-seat-from-li
      margin-bottom 20px
    .exclusive-seat-li-email
      width 400px !important
      margin-bottom 15px !important
    .exclusive-seat-li
      width 400px
    .condition_li
      width 200px
      margin-right 20px
    .exclusive-seat-li-input
      width calc(100% - 100px)
  .email-notice
    margin-left 160px
    padding-bottom 5px
    color $cf-gray4
  .domain_btn
    cursor pointer
  .el-icon-plus
    color $c-main
  .el-icon-minus
    color $c-pink
  .exclusiveSeat-active
    border-color $c-main !important
  .exclusiveSeatBtn
    margin-top 20px
  .filter-tree
    padding-bottom 5px
    max-height 280px
    max-width 400px
    min-width 250px
    overflow auto
    border none
</style>
